<template>
  <div class="permissions-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>权限管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增权限
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="权限名称">
          <el-input v-model="searchForm.name" placeholder="请输入权限名称" clearable />
        </el-form-item>
        <el-form-item label="权限编码">
          <el-input v-model="searchForm.code" placeholder="请输入权限编码" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="name" label="权限名称" />
        <el-table-column prop="code" label="权限编码" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" link size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑权限对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="permissionFormRef"
        :model="permissionForm"
        :rules="permissionFormRules"
        label-width="100px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="permissionForm.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限编码" prop="code">
          <el-input v-model="permissionForm.code" placeholder="请输入权限编码" />
          <div style="color: #909399; font-size: 12px; margin-top: 4px">
            权限编码应为英文，如：user:create、user:update
          </div>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="permissionForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入权限描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  getPermissionList,
  createPermission,
  updatePermission,
  deletePermission,
  getPermissionDetail,
  type Permission,
  type CreatePermissionParams,
  type UpdatePermissionParams
} from '@/api/permissions'
import { formatDate, isPermissionCode } from '@/utils'

const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const permissionFormRef = ref<FormInstance>()

const searchForm = reactive({
  name: '',
  code: ''
})

const tableData = ref<Permission[]>([])

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const permissionForm = reactive<CreatePermissionParams & { id?: string }>({
  name: '',
  code: '',
  description: ''
})

const permissionFormRules: FormRules = {
  name: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
  code: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    {
      validator: (_rule: any, value: string, callback: Function) => {
        if (!value) {
          callback()
        } else if (!isPermissionCode(value)) {
          callback(new Error('权限编码只能包含小写字母、数字、冒号、下划线和连字符'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  description: []
}

const dialogTitle = computed(() => (isEdit.value ? '编辑权限' : '新增权限'))

// 加载权限列表
const loadPermissionList = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.page,
      pageSize: pagination.size
    }
    if (searchForm.name) {
      params.name = searchForm.name
    }
    if (searchForm.code) {
      params.code = searchForm.code
    }

    const res = await getPermissionList(params)
    tableData.value = res.data.list
    pagination.total = res.data.total
    pagination.page = res.data.page
    pagination.size = res.data.pageSize
  } catch (error: any) {
    ElMessage.error(error.message || '加载权限列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadPermissionList()
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.code = ''
  pagination.page = 1
  loadPermissionList()
}

// 新增权限
const handleAdd = () => {
  isEdit.value = false
  dialogVisible.value = true
  resetPermissionForm()
}

// 编辑权限
const handleEdit = async (row: Permission) => {
  isEdit.value = true
  dialogVisible.value = true
  loading.value = true
  try {
    const res = await getPermissionDetail({ id: row.id })
    const permission = res.data
    permissionForm.id = permission.id
    permissionForm.name = permission.name
    permissionForm.code = permission.code
    permissionForm.description = permission.description || ''
  } catch (error: any) {
    ElMessage.error(error.message || '获取权限详情失败')
    dialogVisible.value = false
  } finally {
    loading.value = false
  }
}

// 删除权限
const handleDelete = (row: Permission) => {
  ElMessageBox.confirm(`确定要删除权限 "${row.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await deletePermission({ id: row.id })
        ElMessage.success('删除成功')
        loadPermissionList()
      } catch (error: any) {
        ElMessage.error(error.message || '删除失败')
      }
    })
    .catch(() => {})
}

// 重置表单
const resetPermissionForm = () => {
  permissionForm.name = ''
  permissionForm.code = ''
  permissionForm.description = ''
  permissionForm.id = undefined
  permissionFormRef.value?.clearValidate()
}

// 提交表单
const handleSubmit = async () => {
  if (!permissionFormRef.value) return

  await permissionFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (isEdit.value) {
          // 更新权限
          const updateParams: UpdatePermissionParams = {
            id: permissionForm.id!,
            name: permissionForm.name,
            code: permissionForm.code,
            description: permissionForm.description
          }
          await updatePermission(updateParams)
          ElMessage.success('更新成功')
        } else {
          // 创建权限
          const createParams: CreatePermissionParams = {
            name: permissionForm.name,
            code: permissionForm.code,
            description: permissionForm.description
          }
          await createPermission(createParams)
          ElMessage.success('创建成功')
        }
        dialogVisible.value = false
        loadPermissionList()
      } catch (error: any) {
        ElMessage.error(error.message || (isEdit.value ? '更新失败' : '创建失败'))
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  resetPermissionForm()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  loadPermissionList()
}

// 页码改变
const handlePageChange = (page: number) => {
  pagination.page = page
  loadPermissionList()
}

onMounted(() => {
  loadPermissionList()
})
</script>

<style scoped lang="scss">
.permissions-page {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-form {
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
